package com.sarc.games;

import java.util.ArrayList;

//Helper class that creates animation according to frame time and updates
public abstract class GameAction {

	private double lastProgress, progress;
	private long lastTime, timeAllowed;
	
	protected GameAction(long timeAllowed)
	{
		lastProgress = progress = 0;
		lastTime = 0;
		this.timeAllowed = timeAllowed;
	}
	
	public boolean resolve(long frameTime)
	{
		boolean resolved;
		if (lastTime > 0 && progress < 100)
		{
			lastProgress = progress;
			double deltaProgress = (double)((frameTime-lastTime)/(double)timeAllowed);
			if (deltaProgress + lastProgress > 1)
			{
				progress = 1;
			}
			else
			{
				progress += deltaProgress;
			}
			resolved = true;
		}
		else
		{	
			resolved = false;
		}
		lastTime = frameTime;
		return resolved;
	}
	
	protected double currentProgress()
	{
		return progress;
	}
	
	protected double deltaProgress()
	{
		return progress - lastProgress;
	}
	
	protected long duration()
	{
		return timeAllowed;
	}
	
	public boolean shouldRemove()
	{
		return progress >= 1;
	}
	
	public static void cleanGameAction(ArrayList<?> gameActions)
	{
		for (int i = 0; i < gameActions.size(); )
		{
			if (gameActions.get(i) instanceof GameAction)
			{	
				if (((GameAction)gameActions.get(i)).shouldRemove())
				{
					gameActions.remove(i);
				}
				else 
				{
					i++;
				}
			}
			else
			{
				gameActions.remove(i);
			}
		}
	}
}
